<script setup lang="ts">
import type { EchartsUIType } from '@vben/plugins/echarts';

import { nextTick, onMounted, reactive, ref } from 'vue';

import { Page } from '@vben/common-ui';
import { IconifyIcon } from '@vben/icons';
import { EchartsUI, useEcharts } from '@vben/plugins/echarts';

import {
  Button,
  Col,
  DatePicker,
  Input,
  message,
  Row,
  Select,
  SelectOption,
  Space,
  Table,
  Tag,
} from 'ant-design-vue';
import dayjs from 'dayjs';

import {
  callNextTicket as callNextTicketApi,
  completeService as completeServiceApi,
  confirmBooking as confirmBookingApi,
  getBookingList,
  getBookingStats,
  getBookingTrends,
  getBusinessContexts,
  getServiceWindows,
  markNoShow as markNoShowApi,
  startService as startServiceApi,
  updateWindowStatus,
} from '#/api/booking';
import StatisticCard from '#/components/hotel/StatisticsCard.vue';

// 统计数据
const stats = ref({
  totalBookings: 0,
  confirmedBookings: 0,
  completedBookings: 0,
  averageWaitTime: 0,
});

// 服务窗口
const serviceWindows = ref([]);
const businessContexts = ref([]);

// 预约列表
const bookings = ref([]);
const loading = ref(false);
const dateRange = ref<any>(undefined);

const queryParams = reactive({
  page: 1,
  pageSize: 10,
  contextId: '',
  status: '',
  customerName: '',
  startDate: '',
  endDate: '',
});

const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
});

// 表格列定义
const bookingColumns = [
  {
    title: '预约号',
    dataIndex: 'bookingNo',
    key: 'bookingNo',
    width: 120,
  },
  {
    title: '客户姓名',
    dataIndex: 'customerName',
    key: 'customerName',
    width: 100,
  },
  {
    title: '手机号',
    dataIndex: 'phoneNumber',
    key: 'phoneNumber',
    width: 120,
  },
  {
    title: '服务项目',
    dataIndex: 'serviceName',
    key: 'serviceName',
    width: 150,
  },
  {
    title: '预约时间',
    dataIndex: 'bookingDate',
    key: 'bookingDate',
    width: 120,
    customRender: ({ text, record }: any) => `${text} ${record.timeSlot}`,
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    width: 100,
  },
  {
    title: '取号',
    dataIndex: 'queueTicket',
    key: 'queueTicket',
    width: 80,
  },
  {
    title: '操作',
    key: 'actions',
    width: 200,
    fixed: 'right',
  },
];

// 图表引用
const trendChartRef = ref<EchartsUIType>();
const pieChartRef = ref<EchartsUIType>();
const { renderEcharts: renderTrendChart } = useEcharts(trendChartRef);
const { renderEcharts: renderPieChart } = useEcharts(pieChartRef);

// 加载统计数据
const loadStats = async () => {
  try {
    const statsData = await getBookingStats({
      startDate: dayjs().format('YYYY-MM-DD'),
      endDate: dayjs().format('YYYY-MM-DD'),
    });
    stats.value = statsData;
  } catch (error) {
    console.error('加载统计数据失败:', error);
  }
};

// 加载服务窗口
const loadServiceWindows = async () => {
  try {
    const windows = await getServiceWindows();
    serviceWindows.value = windows;
  } catch (error) {
    console.error('加载服务窗口失败:', error);
  }
};

// 加载业务场景
const loadBusinessContexts = async () => {
  try {
    const contexts = await getBusinessContexts();
    businessContexts.value = contexts;
  } catch (error) {
    console.error('加载业务场景失败:', error);
  }
};

// 加载预约列表
const loadBookings = async () => {
  try {
    loading.value = true;
    const result = await getBookingList(queryParams);
    bookings.value = result.list;
    pagination.total = result.total;
  } catch (error) {
    console.error('加载预约列表失败:', error);
    message.error('加载预约列表失败');
  } finally {
    loading.value = false;
  }
};

// 刷新预约列表
const refreshBookings = () => {
  loadBookings();
};

// 处理日期变化
const handleDateChange = (dates: any) => {
  if (dates && dates.length === 2) {
    queryParams.startDate = dayjs(dates[0]).format('YYYY-MM-DD');
    queryParams.endDate = dayjs(dates[1]).format('YYYY-MM-DD');
  } else {
    queryParams.startDate = '';
    queryParams.endDate = '';
  }
  loadBookings();
};

// 处理表格变化
const handleTableChange = (pag: any) => {
  queryParams.page = pag.current;
  queryParams.pageSize = pag.pageSize;
  pagination.current = pag.current;
  pagination.pageSize = pag.pageSize;
  loadBookings();
};

// 确认预约
const confirmBooking = async (record: any) => {
  try {
    await confirmBookingApi(record.id);
    message.success('预约已确认');
    loadBookings();
    loadStats();
  } catch (error) {
    console.error('确认预约失败:', error);
    message.error('确认预约失败');
  }
};

// 开始服务
const startService = async (record: any) => {
  try {
    await startServiceApi(record.id);
    message.success('服务已开始');
    loadBookings();
    loadServiceWindows();
  } catch (error) {
    console.error('开始服务失败:', error);
    message.error('开始服务失败');
  }
};

// 完成服务
const completeService = async (record: any) => {
  try {
    await completeServiceApi(record.id);
    message.success('服务已完成');
    loadBookings();
    loadStats();
  } catch (error) {
    console.error('完成服务失败:', error);
    message.error('完成服务失败');
  }
};

// 标记爽约
const markNoShow = async (record: any) => {
  try {
    await markNoShowApi(record.id);
    message.success('已标记为爽约');
    loadBookings();
    loadStats();
  } catch (error) {
    console.error('标记爽约失败:', error);
    message.error('标记爽约失败');
  }
};

// 叫号
const callNextTicket = async (windowId: string) => {
  try {
    await callNextTicketApi(windowId);
    message.success('已叫号');
    loadServiceWindows();
  } catch (error) {
    console.error('叫号失败:', error);
    message.error('叫号失败');
  }
};

// 完成当前服务
const completeCurrentService = async (windowId: string) => {
  // 这里需要根据窗口ID找到对应的预约记录
  console.log('完成当前服务:', windowId);
};

// 切换窗口状态
const toggleWindowStatus = async (window: any) => {
  try {
    const newStatus = window.status === 'OFFLINE' ? 'IDLE' : 'OFFLINE';
    newStatuswindow.statusnewStatuswindow.status;
    await updateWindowStatus(window.id, newStatus);
    message.success(`窗口已${newStatus === 'OFFLINE' ? '离线' : '上线'}`);
    loadServiceWindows();
  } catch (error) {
    console.error('切换窗口状态失败:', error);
    message.error('切换窗口状态失败');
  }
};

// 查看预约详情
const viewBookingDetail = (record: any) => {
  console.log('查看预约详情:', record);
};

// 状态相关方法
const getWindowStatusClass = (status: string) => {
  return `window-${status.toLowerCase()}`;
};

const getWindowStatusColor = (status: string) => {
  const colorMap: Record<string, string> = {
    BUSY: 'green',
    IDLE: 'blue',
    OFFLINE: 'red',
  };
  return colorMap[status] || 'default';
};

const getWindowStatusText = (status: string) => {
  const textMap: Record<string, string> = {
    BUSY: '服务中',
    IDLE: '空闲',
    OFFLINE: '离线',
  };
  return textMap[status] || '未知';
};

const getBookingStatusColor = (status: string) => {
  const colorMap: Record<string, string> = {
    PENDING: 'orange',
    CONFIRMED: 'blue',
    IN_PROGRESS: 'green',
    COMPLETED: 'default',
    CANCELLED: 'red',
    NO_SHOW: 'red',
  };
  return colorMap[status] || 'default';
};

const getBookingStatusText = (status: string) => {
  const textMap: Record<string, string> = {
    PENDING: '待确认',
    CONFIRMED: '已确认',
    IN_PROGRESS: '进行中',
    COMPLETED: '已完成',
    CANCELLED: '已取消',
    NO_SHOW: '爽约',
  };
  return textMap[status] || '未知';
};

const formatTime = (time: string) => {
  return dayjs(time).format('HH:mm:ss');
};

// 初始化图表
const initCharts = async () => {
  await nextTick();

  // 初始化趋势图
  const trendOption = {
    grid: {
      bottom: 20,
      containLabel: true,
      left: '3%',
      right: '4%',
      top: '10%',
    },
    legend: {
      data: ['预约数', '完成数'],
      top: 0,
    },
    series: [
      {
        data: [],
        itemStyle: {
          color: '#5ab1ef',
        },
        name: '预约数',
        smooth: true,
        type: 'line',
      },
      {
        data: [],
        itemStyle: {
          color: '#019680',
        },
        name: '完成数',
        smooth: true,
        type: 'line',
      },
    ],
    tooltip: {
      axisPointer: {
        lineStyle: {
          color: '#019680',
          width: 1,
        },
      },
      trigger: 'axis',
      triggertrigger,
    },
    xAxis: {
      axisTick: {
        show: false,
      },
      boundaryGap: false,
      data: [],
      splitLine: {
        lineStyle: {
          type: 'solid',
          width: 1,
        },
        show: true,
        showshow,
      },
      type: 'category',
      typetype,
    },
    yAxis: [
      {
        axisTick: {
          show: false,
        },
        splitArea: {
          show: true,
        },
        splitNumber: 4,
        type: 'value',
      },
    ],
  };
  renderTrendChart(trendOption);

  // 初始化饼图
  const pieOption = {
    legend: {
      bottom: 0,
      data: ['温泉洗浴', '酒店公寓', '餐厅服务', '宠物医疗'],
    },
    series: [
      {
        data: [
          { name: '温泉洗浴', value: 0 },
          { name: '酒店公寓', value: 0 },
          { name: '餐厅服务', value: 0 },
          { name: '宠物医疗', value: 0 },
        ],
        itemStyle: {
          borderRadius: 10,
          borderWidth: 2,
        },
        radius: '50%',
        type: 'pie',
      },
    ],
    tooltip: {
      trigger: 'item',
    },
  };
  renderPieChart(pieOption);
};

// 加载图表数据
const loadChartData = async () => {
  try {
    const trends = await getBookingTrends({
      startDate: dayjs().subtract(7, 'day').format('YYYY-MM-DD'),
      endDate: dayjs().format('YYYY-MM-DD'),
      groupBy: 'day',
    });

    // 更新趋势图数据
    const trendOption = {
      grid: {
        bottom: 30,
        containLabel: true,
        left: '3%',
        right: '4%',
        top: '3%',
      },
      legend: {
        data: ['预约数', '完成数'],
        top: 0,
      },
      series: [
        {
          data: trends.map((item) => item.bookings),
          itemStyle: {
            color: '#5ab1ef',
          },
          name: '预约数',
          smooth: true,
          type: 'line',
        },
        {
          data: trends.map((item) => item.completed),
          itemStyle: {
            color: '#019680',
          },
          name: '完成数',
          smooth: true,
          type: 'line',
        },
      ],
      tooltip: {
        axisPointer: {
          lineStyle: {
            color: '#019680',
            width: 1,
          },
        },
        trigger: 'axis',
        triggertrigger,
      },
      xAxis: {
        axisTick: {
          show: false,
        },
        boundaryGap: false,
        data: trends.map((item) => item.date),
        splitLine: {
          lineStyle: {
            type: 'solid',
            width: 1,
          },
          show: true,
          showshow,
        },
        type: 'category',
        typetype,
      },
      yAxis: [
        {
          axisTick: {
            show: false,
          },
          splitArea: {
            show: true,
          },
          splitNumber: 4,
          type: 'value',
        },
      ],
    };
    renderTrendChart(trendOption);

    // 更新饼图数据（基于业务场景统计）
    const pieData = businessContexts.value.map((context) => ({
      name: context.name,
      value: Math.floor(Math.random() * 100) + 10, // 模拟数据
    }));

    const pieOption = {
      legend: {
        bottom: 0,
        data: pieData.map((item) => item.name),
      },
      series: [
        {
          data: pieData,
          itemStyle: {
            borderRadius: 10,
            borderWidth: 2,
          },
          radius: '50%',
          type: 'pie',
        },
      ],
      tooltip: {
        trigger: 'item',
      },
    };
    renderPieChart(pieOption);
  } catch (error) {
    console.error('加载图表数据失败:', error);
  }
};

onMounted(async () => {
  await initCharts();
  await Promise.all([
    loadStats(),
    loadServiceWindows(),
    loadBusinessContexts(),
    loadBookings(),
    loadChartData(),
  ]);
});
</script>

<template>
  <div class="booking-admin">
    <Page title="预约排队管理" content="多业态预约排队系统管理后台">
      <div class="admin-container">
        <!-- 统计卡片 -->
        <div class="stats-section">
          <Row :gutter="16">
            <Col :span="6">
              <StatisticCard
                title="今日预约"
                :value="stats.totalBookings"
                :precision="0"
                prefix=""
                suffix="个"
                color="#3b82f6"
              />
            </Col>
            <Col :span="6">
              <StatisticCard
                title="已确认"
                :value="stats.confirmedBookings"
                :precision="0"
                prefix=""
                suffix="个"
                color="#10b981"
              />
            </Col>
            <Col :span="6">
              <StatisticCard
                title="已完成"
                :value="stats.completedBookings"
                :precision="0"
                prefix=""
                suffix="个"
                color="#f59e0b"
              />
            </Col>
            <Col :span="6">
              <StatisticCard
                title="平均等待"
                :value="stats.averageWaitTime"
                :precision="0"
                prefix=""
                suffix="分钟"
                color="#ef4444"
              />
            </Col>
          </Row>
        </div>

        <!-- 服务窗口状态 -->
        <div class="windows-section">
          <h3 class="section-title">服务窗口状态</h3>
          <div class="windows-grid">
            <div
              v-for="window in serviceWindows"
              :key="window.id"
              class="window-card"
              :class="getWindowStatusClass(window.status)"
            >
              <div class="window-header">
                <h4 class="window-name">{{ window.name }}</h4>
                <Tag :color="getWindowStatusColor(window.status)">
                  {{ getWindowStatusText(window.status) }}
                </Tag>
              </div>

              <div v-if="window.currentCustomer" class="current-customer">
                <div class="customer-info">
                  <span class="ticket-number">{{
                    window.currentCustomer.ticketNumber
                  }}</span>
                  <span class="customer-name">{{
                    window.currentCustomer.customerName
                  }}</span>
                </div>
                <div class="service-time">
                  开始时间: {{ formatTime(window.currentCustomer.startTime) }}
                </div>
              </div>

              <div v-else class="no-customer">
                <IconifyIcon icon="mdi:account-off" />
                <span>暂无客户</span>
              </div>

              <div class="window-actions">
                <Button
                  v-if="window.status === 'IDLE'"
                  type="primary"
                  size="small"
                  @click="callNextTicket(window.id)"
                >
                  叫号
                </Button>
                <Button
                  v-if="window.status === 'BUSY'"
                  type="default"
                  size="small"
                  @click="completeCurrentService(window.id)"
                >
                  完成服务
                </Button>
                <Button
                  type="link"
                  size="small"
                  @click="toggleWindowStatus(window)"
                >
                  {{ window.status === 'OFFLINE' ? '上线' : '离线' }}
                </Button>
              </div>
            </div>
          </div>
        </div>

        <!-- 预约管理 -->
        <div class="bookings-section">
          <div class="section-header">
            <h3 class="section-title">预约管理</h3>
            <div class="section-actions">
              <Button @click="refreshBookings" :loading="loading">
                <IconifyIcon icon="mdi:refresh" />
                刷新
              </Button>
            </div>
          </div>

          <div class="filters">
            <Row :gutter="16">
              <Col :span="6">
                <Select
                  v-model:value="queryParams.contextId"
                  placeholder="选择业务场景"
                  allow-clear
                  @change="loadBookings"
                >
                  <SelectOption
                    v-for="context in businessContexts"
                    :key="context.id"
                    :value="context.id"
                  >
                    {{ context.name }}
                  </SelectOption>
                </Select>
              </Col>
              <Col :span="6">
                <Select
                  v-model:value="queryParams.status"
                  placeholder="预约状态"
                  allow-clear
                  @change="loadBookings"
                >
                  <SelectOption value="PENDING">待确认</SelectOption>
                  <SelectOption value="CONFIRMED">已确认</SelectOption>
                  <SelectOption value="IN_PROGRESS">进行中</SelectOption>
                  <SelectOption value="COMPLETED">已完成</SelectOption>
                  <SelectOption value="CANCELLED">已取消</SelectOption>
                </Select>
              </Col>
              <Col :span="6">
                <DatePicker.RangePicker
                  v-model:value="dateRange"
                  :placeholder="['开始日期', '结束日期']"
                  @change="handleDateChange"
                />
              </Col>
              <Col :span="6">
                <Input
                  v-model:value="queryParams.customerName"
                  placeholder="客户姓名"
                  @press-enter="loadBookings"
                />
              </Col>
            </Row>
          </div>

          <Table
            :columns="bookingColumns"
            :data-source="bookings"
            :loading="loading"
            :pagination="pagination"
            @change="handleTableChange"
            row-key="id"
          >
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'status'">
                <Tag :color="getBookingStatusColor(record.status)">
                  {{ getBookingStatusText(record.status) }}
                </Tag>
              </template>

              <template v-else-if="column.key === 'actions'">
                <Space>
                  <Button
                    v-if="record.status === 'PENDING'"
                    type="primary"
                    size="small"
                    @click="confirmBooking(record)"
                  >
                    确认
                  </Button>
                  <Button
                    v-if="record.status === 'CONFIRMED'"
                    type="default"
                    size="small"
                    @click="startService(record)"
                  >
                    开始服务
                  </Button>
                  <Button
                    v-if="record.status === 'IN_PROGRESS'"
                    type="success"
                    size="small"
                    @click="completeService(record)"
                  >
                    完成
                  </Button>
                  <Button
                    v-if="
                      record.status === 'CONFIRMED' ||
                      record.status === 'PENDING'
                    "
                    type="warning"
                    size="small"
                    @click="markNoShow(record)"
                  >
                    爽约
                  </Button>
                  <Button
                    type="link"
                    size="small"
                    @click="viewBookingDetail(record)"
                  >
                    详情
                  </Button>
                </Space>
              </template>
            </template>
          </Table>
        </div>

        <!-- 报表分析 -->
        <div class="reports-section">
          <h3 class="section-title">报表分析</h3>
          <Row :gutter="16">
            <Col :span="12">
              <div class="chart-card">
                <h4>预约趋势</h4>
                <EchartsUI ref="trendChartRef" class="chart-container" />
              </div>
            </Col>
            <Col :span="12">
              <div class="chart-card">
                <h4>业务场景分布</h4>
                <EchartsUI ref="pieChartRef" class="chart-container" />
              </div>
            </Col>
          </Row>
        </div>
      </div>
    </Page>
  </div>
</template>

<style scoped>
.booking-admin {
  padding: 20px;
}

.admin-container {
  max-width: 1400px;
  margin: 0 auto;
}

.stats-section {
  margin-bottom: 32px;
}

.section-title {
  margin-bottom: 16px;
  font-size: 18px;
  font-weight: 600;
  color: #1f2937;
}

.windows-section,
.bookings-section,
.reports-section {
  margin-bottom: 32px;
}

.section-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 16px;
}

.windows-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 16px;
}

.window-card {
  padding: 16px;
  background: white;
  border: 1px solid #e5e7eb;
  border-radius: 12px;
  transition: all 0.3s ease;
}

.window-card.window-busy {
  border-left: 4px solid #10b981;
}

.window-card.window-idle {
  border-left: 4px solid #3b82f6;
}

.window-card.window-offline {
  border-left: 4px solid #ef4444;
  opacity: 0.6;
}

.window-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 12px;
}

.window-name {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #1f2937;
}

.current-customer {
  padding: 12px;
  margin-bottom: 12px;
  background: #f0f9ff;
  border-radius: 8px;
}

.customer-info {
  display: flex;
  gap: 12px;
  align-items: center;
  margin-bottom: 8px;
}

.ticket-number {
  font-size: 18px;
  font-weight: 700;
  color: #3b82f6;
}

.customer-name {
  font-weight: 500;
  color: #1f2937;
}

.service-time {
  font-size: 14px;
  color: #6b7280;
}

.no-customer {
  display: flex;
  gap: 8px;
  align-items: center;
  justify-content: center;
  padding: 20px;
  font-size: 14px;
  color: #6b7280;
  text-align: center;
}

.window-actions {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.filters {
  padding: 16px;
  margin-bottom: 16px;
  background: white;
  border: 1px solid #e5e7eb;
  border-radius: 8px;
}

.chart-card {
  padding: 20px;
  background: white;
  border: 1px solid #e5e7eb;
  border-radius: 12px;
}

.chart-card h4 {
  margin: 0 0 16px;
  font-size: 16px;
  font-weight: 600;
  color: #1f2937;
}

.chart-container {
  height: 300px;
}
</style>
